package com.yiren.manager.ctrl.elder;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrBed;
import com.yiren.entity.YrBedRetain;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderOutOrder;
import com.yiren.entity.YrStaffInfo;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.elder.YrElderOutOrderForm;
import com.yiren.manager.service.iface.beds.YrBedService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrBedRetainService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderOutOrderService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.messhall.YrMealCardService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("elderOutOrder")
@Controller
public class YrElderOutOrderController extends GenericController<YrElderOutOrderForm, YrElderOutOrder>{

	@Autowired
	private YrElderOutOrderService selfService;
	
	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;
	
	@Autowired
	private YrStaffInfoService staffInfoService;
	
	@Autowired
	private YrElderService elderService;
	
	@Autowired
	private YrMealCardService mealCardService;
	
	@Autowired
	private YrBedService bedService;
	
	@Autowired
	private YrBedRetainService bedRetainService;
	
	//保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrElderOutOrderForm> save(String data) throws SwallowException, MyException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		HTTPResult<YrElderOutOrderForm> result = new HTTPResult<YrElderOutOrderForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrElderOutOrderForm form = tool.mapper("elderOutOrder", YrElderOutOrderForm.class);
		String sqlWhere = "elder_id=?1 AND be_status=0";
		QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class, sqlWhere, new Object[]{form.getElderId()});
		if(qrElderBeHospital.getTotalRecord()==0){
			throwExp("查询不到该老者相关住院信息");
		}
		//检查是否还有欠费记录
//		sqlWhere = "elder_id=?1 AND status=0";
//		QueryResult<YrElderArrearage> qrElderArrearage = elderArrearageService.find(YrElderArrearage.class,sqlWhere,new Object[]{form.getElderId()});
//		if(!qrElderArrearage.getResultList().isEmpty()){
//			throwExp("该老者尚有欠费未结清，请先补缴欠费");
//		}
		YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
		YrElder elder = elderService.findOne(elderBeHospital.getElderId());
		if(null==elder){
			throwExp("查询不到相关老者信息");
		}
		sqlWhere = "retain_status<>2 AND be_hospital_id=?1";
		QueryResult<YrBedRetain> qrBedRetain = bedRetainService.find(YrBedRetain.class, sqlWhere,new Object[]{elderBeHospital.getBeHospitalId()});
		if(!qrBedRetain.getResultList().isEmpty()){
			throwExp("该老者尚有保床未结束，请先结束保床");
		}
		if(elderBeHospital.getBedStatus()==2){//如果已经出院
			throwExp("该老者已经出院");
		}
		sqlWhere = "be_hospital_id=?1";
		QueryResult<YrElderOutOrder> qrElderOutOrder = selfService.find(YrElderOutOrder.class, sqlWhere, new Object[]{form.getBeHospitalId()});
		if(qrElderOutOrder.getTotalRecord()>0){
			throwExp("该老者已提交出院，请勿重复提交");
		}
		if(null==form){
			throwExp("param.error");
		}
		if(form.getElderOutOrderId().isEmpty()){
			form.setElderOutOrderId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
			form.setOrderTime(form.getCreateTime());
//			form.setStatus(0);
		}
		form.setUpdateTime(new Date());
		YrElderOutOrder entity = ObjectUtils.objectToObject(form, YrElderOutOrder.class);
		if(entity.getElderOutOrderId().isEmpty()){
			entity.setStatus(0);
		}
		elderBeHospital.setBeStatus(1);//设置为正在出院状态
		elderBeHospital.setBeType(2);//床位状态：0正在住1保留2已出院
		elderBeHospital.setOutDate(new Date());
		
		elder.setBeHospitalStatus(2);//设置为出院状态
		elder.setUpdateTime(new Date());
		
		//床位设置为空闲状态
		YrBed bed = bedService.findOne(elderBeHospital.getBedId());
		if(null!=bed){
			bed.setUpdateTime(new Date());
			bed.setUseStatus(0);
		}
		bedService.save(bed);
		elderService.save(elder);
		elderBeHospitalService.save(elderBeHospital);
		selfService.save(entity);//设置为预约状态
		
		return result;
	}
	
	@RequestMapping("findBySubjectRoomId")
	@ResponseBody
	public HTTPResult<YrElderOutOrderForm> findBySubjectRoomId(String subjectRoomId,Integer status) throws Exception{
		HTTPResult<YrElderOutOrderForm> result = new HTTPResult<YrElderOutOrderForm>();
		String sqlWhere = "subject_room_id=?1 AND status=?2";
		QueryResult<YrElderOutOrder> qrElderOutOrder = selfService.find(YrElderOutOrder.class, sqlWhere, new Object[]{subjectRoomId,status});
		
		List<YrElderOutOrderForm> formList = new ArrayList<YrElderOutOrderForm>();
		
		for(YrElderOutOrder entity : qrElderOutOrder.getResultList()){
			YrElderOutOrderForm form = toForm(entity);
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(entity.getBeHospitalId());
			if(elderBeHospital!=null){
				YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class);
				
				sqlWhere = "subject_room_id=?1 AND manager_of_subject_room=1 AND status=0";
				
				QueryResult<YrStaffInfo> qrStaffInfo = staffInfoService.find(YrStaffInfo.class, sqlWhere, new Object[]{elderBeHospital.getSubjectRoomId()});
				if(qrStaffInfo.getTotalRecord()>0){
					elderBeHospitalForm.setSubjectRoomManager(qrStaffInfo.getResultList().get(0).getName());
				}
				form.setElderBeHospitalForm(elderBeHospitalForm);
				YrElder elder = elderService.findOne(elderBeHospital.getElderId());
				if(null!=elder){
					form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
				}
			}
			
			formList.add(form);
		}
		result.setData(formList);
		
		return result;
	}
	
	@RequestMapping("findAll")
	@ResponseBody
	public HTTPResult<YrElderOutOrderForm> findAll(Integer status,String subjectRoomId) throws Exception{
		HTTPResult<YrElderOutOrderForm> result = new HTTPResult<YrElderOutOrderForm>();
		String sqlWhere = "";
		QueryResult<YrElderOutOrder> qrElderOutOrder = null;
		if(subjectRoomId!=null){
			sqlWhere = "status=?1 AND subject_room_id=?2";
			qrElderOutOrder = selfService.find(YrElderOutOrder.class, sqlWhere, new Object[]{status,subjectRoomId});
		}else{
			sqlWhere = "status=?1";
			qrElderOutOrder = selfService.find(YrElderOutOrder.class, sqlWhere, new Object[]{status});
		}
		
		List<YrElderOutOrderForm> formList = new ArrayList<YrElderOutOrderForm>();
		
		for(YrElderOutOrder entity : qrElderOutOrder.getResultList()){
			YrElderOutOrderForm form = toForm(entity);
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(entity.getBeHospitalId());
			if(elderBeHospital!=null){
				YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class);
				
				sqlWhere = "subject_room_id=?1 AND manager_of_subject_room=1 AND status=0";
				
				QueryResult<YrStaffInfo> qrStaffInfo = staffInfoService.find(YrStaffInfo.class, sqlWhere, new Object[]{elderBeHospital.getSubjectRoomId()});
				if(qrStaffInfo.getTotalRecord()>0){
					elderBeHospitalForm.setSubjectRoomManager(qrStaffInfo.getResultList().get(0).getName());
				}
				form.setElderBeHospitalForm(elderBeHospitalForm);
			}
			YrElder elder = elderService.findOne(entity.getElderId());
			if(null!=elder){
				form.setElderForm(ObjectUtils.objectToObject(elder,YrElderForm.class));
			}
			
			formList.add(form);
		}
		result.setData(formList);
		
		return result;
	}
	
	/**
	 * 设置为已经对账
	 * @param beHospitalId
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("setCheck")
	@ResponseBody
	public HTTPResult<YrElderOutOrderForm> setCheck(String beHospitalId) throws MyException{
		HTTPResult<YrElderOutOrderForm> result = new HTTPResult<YrElderOutOrderForm>();
		String sqlWhere = "be_hospital_id=?1 AND status=0";
		QueryResult<YrElderOutOrder> qr = selfService.find(YrElderOutOrder.class, sqlWhere, new Object[]{beHospitalId});
		if(qr.getTotalRecord()>0){
			YrElderOutOrder entity = qr.getResultList().get(0);
			entity.setStatus(1);//设置已经对账状态
					
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(beHospitalId);
			if(null==elderBeHospital){
				throwExp("查询不到相关入院登记信息，请检查数据");
			}
		
			selfService.save(entity);
		}
		return result;
	}
	
	/**
	 * 出院报告完成
	 * @param beHospitalId
	 * @return
	 * @throws MyException 
	 */
	@RequestMapping("finish")
	@ResponseBody
	public HTTPResult<YrElderOutOrderForm> finish(String beHospitalId) throws MyException{
		HTTPResult<YrElderOutOrderForm> result = new HTTPResult<YrElderOutOrderForm>();
		String sqlWhere = "be_hospital_id=?1 AND status=1";
		QueryResult<YrElderOutOrder> qr = selfService.find(YrElderOutOrder.class, sqlWhere, new Object[]{beHospitalId});
		if(qr.getTotalRecord()>0){
			YrElderOutOrder entity = qr.getResultList().get(0);
			entity.setStatus(2);//设置为失效状态
					
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(beHospitalId);
			if(null==elderBeHospital){
				throwExp("查询不到相关入院登记信息，请检查数据");
			}
		
//			sqlWhere = "card_person_id=?1";
//			QueryResult<YrMealCard> qrMealCard = mealCardService.find(YrMealCard.class, sqlWhere,new Object[]{entity.getElderId()});
//			
//			//将饭卡的赠送余额清零
//			YrMealCard mealCard = qrMealCard.getResultList().get(0);
//			mealCard.setPreBalance(0F);
//			mealCardService.save(mealCard);
			
//			elderBeHospital.setBeStatus(1);//设置为正在出院状态
//			elderBeHospitalService.save(elderBeHospital);
			selfService.save(entity);
		}
		return result;
	}
	
	@Override
	public YrElderOutOrderForm toForm(YrElderOutOrder e) throws Exception {
		YrElderOutOrderForm form = ObjectUtils.objectToObject(e, YrElderOutOrderForm.class);
		return form;
	}

	@Override
	public YrElderOutOrder toEntity(YrElderOutOrderForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
